import { AuthTokenType } from '@/store/reducer/user';
import { LoactionStateType } from '@/components/AuthRoute';
import axios from 'axios';
import { GetToken, RemoveToken } from './storage';
import history from '@/utils/history';
import { Toast } from 'antd-mobile';
import store from '@/store';
import { UpdateTokenAction } from '@/store/action/login';
// 请求基地址
export const baseURL = 'http://geek.itheima.net';

const http = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
http.interceptors.request.use(
  function (config) {
    const { token } = GetToken();
    if (token) {
      //!是非null和非undefined的类型断言，所以下面的写法就是对config.headers这个属性进行非空断言。
      config.headers!.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    if (!error.response) {
      //网络超时
      Toast.show('网络开小差了 请检查你的网络!');
    } else {
      if (error.response && error.response.status === 401) {
        //token超时
        const refresh_token = GetToken().refresh_token;
        if (refresh_token) {
          try {
            const result = await axios({
              url: `${baseURL}/v1_0/authorizations`,
              method: 'put',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                Authorization: `Bearer ${refresh_token}`,
              },
            });

            /** 更新Token */
            store.dispatch(
              UpdateTokenAction({
                token: result.data.data.token,
                refresh_token,
              })
            );
            return http(error.config);
          } catch (err) {
            /** 清空Redux以及本地储存的Token */
            RemoveToken();
            store.dispatch({
              type: 'user/SaveAuthToken',
              payload: {} as AuthTokenType,
            });
            history.push('/login', {
              from: history.location.pathname,
            } as LoactionStateType);
            Toast.show('登录身份已过期,请重新登录!');
          }
        } else {
          /** 清空Redux以及本地储存的Token */
          RemoveToken();
          store.dispatch({
            type: 'user/SaveAuthToken',
            payload: {} as AuthTokenType,
          });
          history.push('/login', {
            from: history.location.pathname,
          } as LoactionStateType);
          Toast.show('登录身份已过期,请重新登录!');
        }
      } else {
        console.dir(error);
        //其余报错
        Toast.show(error.response.data.message);
      }
    }

    return Promise.reject(error.response && error.response.data.message);
  }
);

export default http;
